package com.woniu.zsd.user.service.impl;

import com.woniu.zsd.user.entity.UserLog;
import com.woniu.zsd.user.mapper.UserLogMapper;
import com.woniu.zsd.user.service.IUserLogService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author author
 * @since 2025-03-27
 */
@Service
public class UserLogServiceImpl extends ServiceImpl<UserLogMapper, UserLog> implements IUserLogService {
    @Autowired
    private UserLogMapper userLogMapper;

    private String getClientIp(HttpServletRequest request) {
        String ip = request.getHeader("X-Forwarded-For");
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        // 如果存在多个IP（如通过代理），取第一个IP
        if (ip != null && ip.contains(",")) {
            ip = ip.split(",")[0].trim();
        }
        return ip;
    }
    @Override
    public void addLog(String loginAddress,String id,HttpServletRequest request) {
        UserLog userLog = new UserLog();
        userLog.setUserId(Integer.parseInt(id));
        userLog.setLoginIp(getClientIp(request));
        userLog.setLoginTime(LocalDateTime.now());
        userLog.setLoginAddress(loginAddress);
        userLogMapper.insert(userLog);
        System.out.println("IP为"+getClientIp(request)+"，ID为"+userLog.getUserId()+"的用户在"+userLog.getLoginTime()+"在"+userLog.getLoginAddress()+"登录了");
    }
}
